package com.tang.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

public class QueryUtils {
    private static final String orderByKey = "_orderBy";
    private static final String desc = "desc";
    private static final String asc = "asc";
    private static final String begin = "_begin";
    private static final String end = "_end";


    public static <T> QueryWrapper<T> build(HttpServletRequest request, Class<T> tClass) {
        QueryWrapper<T> res = new QueryWrapper<>();
        doBuild(res, request);
        return res;
    }

    private static <T> void doBuild(QueryWrapper<T> res, HttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameter = parameterNames.nextElement();
            String value = request.getParameter(parameter);
            if (CommonUtils.isEmpty(value)) continue;

            resolveParameterQuery(res, parameter, value);
        }
    }

    private static <T> void resolveParameterQuery(QueryWrapper<T> res, String parameter, String value) {
        if ("pageNo".equals(parameter)) return;
        if ("pageSize".equals(parameter)) return;
        if (orderByKey.equals(parameter)) {
            String[] split = value.split("\\|");
            String column = split[0];
            String orderByType = split[1];
            if (CommonUtils.isEmpty(column) || CommonUtils.isEmpty(orderByType)) return;
            if (desc.equals(orderByType)) {
                res.orderByDesc(column);
            }
            if (asc.equals(orderByType)) {
                res.orderByAsc(column);
            }
        } else if (isLikeCondition(value)) {
            value = resolveLikeValue(value);
            if (CommonUtils.isEmpty(value)) return;
            res.like(parameter, value);
        } else if (isBegin(parameter)) {
            res.ge(parameter, value);
        } else if (isEnd(parameter)) {
            res.le(parameter, value);
        } else {
            res.eq(parameter, value);
        }
    }

    private static boolean isEnd(String parameter) {
        return parameter.endsWith(end);
    }

    private static boolean isBegin(String parameter) {
        return parameter.endsWith(begin);
    }

    private static String resolveLikeValue(String value) {
        return value.replaceAll("\\*", "%");
    }

    private static boolean isLikeCondition(String parameter) {
        return parameter.contains("*");
    }

    public static <T> IPage<T> createPage(Integer pageNo, Integer pageSize, Class<T> sysUserClass) {
        return new Page<>(pageNo, pageSize);
    }
}
